<!--
 * @Author: aster lipian1004@163.com
 * @Date: 2025-02-21 15:11:14
 * @FilePath: \aster-flowable-uniapp\src\pages\process\process-initiation.vue
 * @Description: 发起流程
 * Copyright (c) 2025 by Aster, All Rights Reserved.
-->
<template>
  <view class="process">
    <!-- 导航栏 -->
    <aster-back
      font-color="#606266"
      :show-title="true"
      :title="formTitle"
      style="background-color: #fff"
    />
    <view>
      <!-- 表单内容 -->
      <van-tabs v-model:active="activeTab">
        <van-tab title="发起提交" name="form" key="form">
          <form-render
            ref="formRenderRef"
            v-model:form-data="formData"
            :form-items="_formItems"
            :form-info="_formInfo"
          />
        </van-tab>
        <van-tab title="查看流程" name="process" key="process">
          <flow-render ref="processRenderRef" :data="_process" :active-node-id="activeNodeId" />
        </van-tab>
      </van-tabs>
    </view>
    <!-- 底部操作按钮 -->
    <aster-tabbar
      :customStyle="{
        borderTopLeftRadius: '10px',
        borderTopRightRadius: '10px',
      }"
    >
      <van-button type="primary" block @click="handleSubmit">提交</van-button>
    </aster-tabbar>
  </view>
</template>
<script lang="ts" setup>
  import { onLoad } from '@dcloudio/uni-app';
  import {
    convertDataTypes,
    evaluateFormula,
    setDefaultValue,
    setFormPermission,
  } from '@/utils/workflow';
  import { computed, ref } from 'vue';
  import FormRender from '../form/form-render.vue';
  import FlowRender from '@/components/flow/flow-render.vue';
  import { formSubmitApi, instanceInfoApi, instanceInfoByInstanceIdApi } from '@/api/workflow/task';
  import { isNotEmpty } from '@/utils/is';
  import AsterBack from '@/components/common/aster-back.vue';
  import AsterTabbar from '@/components/common/aster-tabbar.vue';
  import { Toast, Loading, HideLoading } from '@/utils/uniapi/prompt';
  import { router } from '@/utils/router';

  // 活动页签
  const activeTab = ref('form');
  /** 显示 */
  const visible = ref<boolean>(false);
  /** 标题 */
  const formTitle = ref<string>('');
  /** 注册组件 */
  const formRenderRef = ref();
  /** 当前流程节点 */
  const activeNodeId = ref<string[]>([]);
  /** 表单ID */
  const formId = ref<string>('');
  /** 表单数据 */
  const formData = ref<WorkForm.FormDataModel>({});
  /** 表单权限 */
  const formPermission = ref<Process.FormPermissionModel>({});
  /** 表单信息 */
  const formInfo = ref<WorkForm.FormModel>({
    icon: 'iconfont icon-gengduo',
    iconColor: '',
    labelPosition: 'left',
    formName: '未命名表单',
    formItems: [],
    process: {},
    labelWidth: 80,
    listSettings: {
      queryItems: [],
      columns: [],
      sortBy: 'create_time',
      sortDirection: 'desc',
      actions: [],
    },
  });

  /**
   * @description: 表单项
   */
  const _formItems = computed(() => {
    const formItems = JSON.parse(JSON.stringify(formInfo.value.formItems));
    if (formPermission.value && Object.keys(formPermission.value).length > 0) {
      setFormPermission(formItems, formPermission.value, 'root');
    }
    return formItems;
  });

  /**
   * @description 表单基本信息
   */
  const _formInfo = computed(() => {
    const info: WorkForm.BaseInfo = {
      formName: formInfo.value.formName,
      icon: formInfo.value.icon,
      iconColor: formInfo.value.iconColor,
      labelPosition: formInfo.value.labelPosition,
      labelWidth: formInfo.value.labelWidth,
    };
    return info;
  });

  /**
   * @description 流程设计
   */
  const _process = computed(() => {
    return JSON.parse(JSON.stringify(formInfo.value.process));
  });

  /**
   * @description: 提交校验
   * @return {*}
   */
  const submitValidate = () => {
    if (formInfo.value.settings && formInfo.value.settings.submitValidates) {
      const validates = formInfo.value.settings.submitValidates;
      for (let i = 0; i < validates.length; i++) {
        const v = validates[i];
        if (v.enable) {
          const r = evaluateFormula(v.formula, formData.value);
          if (r) {
            Toast(v.errorMessage);
            return false;
          }
        }
      }
    }
    return true;
  };

  /**
   * @description: 验证表单
   * @return {*}
   */
  const validateForm = async (callback: Function) => {
    // 表单校验
    await formRenderRef.value.validate(() => {
      console.log('表单校验通过');
      // 提交校验
      if (submitValidate()) {
        callback();
      }
    });
  };

  /**
   * @description: 提交
   * @return {*}
   */
  const handleSubmit = () => {
    console.log('提交--->', formData.value);
    validateForm(() => {
      let submitFormData = {
        formId: formId.value,
        formStatus: '0',
        formData: formData.value,
      };
      Loading('提交中...');
      // 提交表单
      formSubmitApi(submitFormData).then(() => {
        HideLoading();
        Toast('提交成功', {
          complete: () => {
            visible.value = false;
            router.back();
          },
        });
      });
    });
  };

  /**
   * @description: 加载表单信息
   * @return {*}
   */
  const loadFormInfo = async (code: string) => {
    await instanceInfoApi({ code: code }).then(({ data }) => {
      // 表单配置信息
      formInfo.value = data.formInfo;
      if (data.formInfo.id) {
        formId.value = data.formInfo.id;
      }
      // 流程节点的表单权限
      if (data.formPermission) {
        formPermission.value = data.formPermission;
      }
    });
  };

  /**
   * @description: 初始化
   * @return {*}
   */
  const init = async (code: string) => {
    // 加载表单信息
    await loadFormInfo(code);
    // 表单项默认值
    await setDefaultValue(_formItems.value, formData.value);
    // 标题
    formTitle.value = _formInfo.value.formName + '-新增';
    visible.value = true;
  };

  /**
   * @description: 再次提交表单数据初始化
   * @return {*}
   */
  const initAgain = async (code: string, procInstId: string) => {
    // 加载表单信息
    await getFormData(code, procInstId);
    // 标题
    formTitle.value = _formInfo.value.formName + '-再次提交';
  };

  /**
   * 初始化表单信息
   * @param code
   * @param instanceId
   */
  const getFormData = async (code: string, instanceId: string) => {
    await instanceInfoByInstanceIdApi(code, instanceId).then(({ data }) => {
      // 表单信息
      formInfo.value = data.formInfo;
      if (data.formInfo.id) {
        formId.value = data.formInfo.id;
      }
      // 流程节点的表单权限
      if (data.formPermission) {
        formPermission.value = data.formPermission;
      }
      // 表单数据
      const instanceInfo = data.instanceInfo;
      if (isNotEmpty(instanceInfo)) {
        for (const key in instanceInfo) {
          if (key.indexOf('field') != -1) {
            formData.value[key] = convertDataTypes(
              formInfo.value.formItems,
              key,
              instanceInfo[key],
            );
          }
        }
      }
      visible.value = true;
    });
  };

  /**
   * @description: 页面加载
   * @return {*}
   */
  onLoad((option) => {
    if (option && option.code) {
      if (option.procInstId) {
        initAgain(option.code, option.procInstId);
      } else {
        init(option.code);
      }
    }
  });

  defineExpose({ init, initAgain });
</script>
<style lang="scss" scoped></style>
